import { defineStore } from 'pinia'
import { apiLogin, apiLogout } from '@/apis/login'
import { apiGetUserInfo } from '@/apis/global.js'
import defaultAvatar from '@/assets/images/global/defaultAvatar.jpeg'
import { useRouterStore } from './route'
export const useUserStore = defineStore(
  'user',
  () => {
    const token = ref()
    const userInfo = ref({})
    const avatar = ref('')
    const permissions = ref([])
    const tenantId = ref('')
    const login = (data, loading) => {
      return new Promise(async (resolve, reject) => {
        try {
          loading.value = true
          const { accessToken } = await apiLogin(data)
          // 登录的时候先清空之前的数据
          logout(false)
          token.value = accessToken
          await getUserInfo()
          loading.value = false
          resolve()
        } catch (error) {
          loading.value = false
          reject(error)
        }
      })
    }
    const getUserInfo = async () => {
      const resData = await apiGetUserInfo()
      console.log(resData, 'resData');
      
      userInfo.value = resData
      avatar.value = resData.photo || defaultAvatar
      tenantId.value = resData.tenantId
    }
    const logout = (apiCall = true) => {
      const { routes } = storeToRefs(useRouterStore())
      return new Promise(async (resolve) => {
        if (apiCall) {
          await apiLogout()
        }
        userInfo.value = {}
        token.value = undefined
        permissions.value = []
        tenantId.value = undefined
        routes.value = []
        resolve()
      })
    }
    return {
      token,
      userInfo,
      avatar,
      permissions,
      tenantId,
      login,
      getUserInfo,
      logout,
    }
  },
  {
    persist: {
      enabled: true, //Store中数据持久化生效
    },
  }
)
